package com.xzy.servlet;

import com.xzy.domain.Book;
import com.xzy.domain.BookCartItem;
import com.xzy.domain.BookPage;
import com.xzy.service.IBookCart;
import com.xzy.service.IBookService;
import com.xzy.service.impl.BookCartImpl;
import com.xzy.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/client/cart")
public class CartServlet extends BaseServlet {
    IBookService service = new BookServiceImpl();
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));

        Book book = service.quaryByid(Integer.valueOf(id));
        BookCartItem bookCartItem = new BookCartItem(book.getId(),book.getName(),1,book.getPrice());
        BookPage<Book> page;

        IBookCart cart = (IBookCart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new BookCartImpl();
            req.getSession().setAttribute("cart",cart);
        }
        cart.additems(bookCartItem);//购物车添加商品


        //请求重定向回原网页
    resp.sendRedirect(req.getHeader("Referer"));

    }

    protected void deleteByid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Integer id = Integer.valueOf(req.getParameter("id"));
        //获取session中购物车对象
        IBookCart cart = (IBookCart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new BookCartImpl();
            req.getSession().setAttribute("cart",cart);
        }

        cart.deleteitems(id);
        //请求重定向回原网页
        resp.sendRedirect(req.getHeader("Referer"));
    }

    protected void cleanCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        //获取session中购物车对象
        IBookCart cart = (IBookCart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new BookCartImpl();
            req.getSession().setAttribute("cart",cart);
        }

        cart.clean();

        //请求重定向回原网页
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
